package com.idea.relax.log.config;


import com.idea.relax.log.constant.PropsConstant;
import com.idea.relax.log.props.RelaxLogProperties;
import com.idea.relax.log.support.utils.Func;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;

import java.util.HashMap;
import java.util.Map;

/**
 * @className: RelaxLoggingConfigInitializer
 * @description: RelaxLog的日志初始化器<br />
 * 主要做两件事: <br />
 * 1.自动设置用户应用的logback.xml配置文件；<br />
 * 2.计算用户应用的主启动类所在包路径
 * @author: salad
 * @date: 2022/11/27
 **/
public class RelaxLoggingConfigInitializer implements EnvironmentPostProcessor, Ordered {


	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		MutablePropertySources propertySources = environment.getPropertySources();
		//自动设置用户应用的logback.xml配置文件
		String logging = environment.getProperty("logging.config");
		String enabled = environment.getProperty(RelaxLogProperties.PREFIX + ".enabled");
		if ("false".equals(enabled)) {
			return;
		}
		if (Func.isBlank(logging)) {
			Map<String, Object> loggingConfigSetMap = new HashMap<>(2);
			loggingConfigSetMap.put("logging.config", "classpath:logback/logback.xml");
			propertySources.addLast(new MapPropertySource("RELAX_LOGGING_CONFIG", loggingConfigSetMap));
		}
		//记录用户主启动类所在包路径
		String property = environment.getProperty(PropsConstant.APP_PACKAGE_PREFIX_KEY);
		if (Func.isEmpty(property)) {
			String appPackage = application.getMainApplicationClass().getPackage().getName();
			Map<String, Object> loggingConfigSetMap = new HashMap<>(2);
			loggingConfigSetMap.put(PropsConstant.APP_PACKAGE_PREFIX_KEY, appPackage);
			propertySources.addLast(new MapPropertySource("RELAX_LOGGING_APP_PACKAGE_PREFIX", loggingConfigSetMap));
		}

	}

	@Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE;
	}

}
